package com.cwf.security.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cwf.common.entity.auth.TokenInfo;
import com.cwf.common.enums.ResCodeEnum;
import com.cwf.common.exception.base.MyException;
import com.cwf.common.utils.auth.JwtUtil;
import com.cwf.framework.redis.RedisService;
import com.cwf.security.dao.UserLoginDao;
import com.cwf.security.entity.SecurityUser;
import com.cwf.security.entity.UserLogin;
import com.cwf.security.service.UserLoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * (UserLogin)表服务实现类
 *
 * @author makejava
 * @since 2023-02-17 08:55:42
 */

@Slf4j
@Service("userLoginService")
public class UserLoginServiceImpl extends ServiceImpl<UserLoginDao, UserLogin> implements UserLoginService {





    @Autowired
    AuthenticationManager authenticationManager;

    @Autowired
    RedisService redisService;

    @Override
    public String login(UserLogin user) {

        UsernamePasswordAuthenticationToken token =new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(token);


        if (Objects.isNull(authenticate)){
            log.error("登入失败");
        }else {
            log.info("密码验证成功");
        }

        SecurityUser principal = (SecurityUser) authenticate.getPrincipal();

        TokenInfo tokenInfo = new TokenInfo();

        tokenInfo.setUserId(principal.getUserID());
        tokenInfo.setUserName(principal.getUsername());

        String tokenStr = JwtUtil.getToken(tokenInfo);

        String redisKey = "token:"+principal.getUserID();

       try {
           redisService.setCacheObject(redisKey,tokenStr,7, TimeUnit.DAYS);
       }catch (Exception e){
           throw new MyException("登入失败", ResCodeEnum.LOGIN_ERR.getCode());
       }
        return tokenStr;
    }
}

